package com.whfc.mach.queue;

import com.whfc.common.constant.QueueConst;
import com.whfc.common.obd.ObdDataUtil;
import com.whfc.common.obd.ObdFrameItem;
import com.whfc.common.third.map.MapApi;
import com.whfc.common.third.map.MapLoc;
import com.whfc.common.util.Gps;
import com.whfc.common.util.JSONUtil;
import com.whfc.mach.dto.iot.MachMsg0x05;
import com.whfc.mach.entity.AppDeviceObdLog;
import com.whfc.mach.manager.ObdDataMgr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description: OBD-硬件数据-消费者
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/12/2 11:59
 */
@Component
@RabbitListener(queues = QueueConst.OBD_DATA)
public class ObdDataQueueMessageListener {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ObdDataMgr obdDataMgr;

    @Autowired
    private MapApi mapApi;

    @RabbitHandler
    public void process(String msg) {
        try {
            logger.debug("obd_data,{}", msg);
            MachMsg0x05 reqMsg = JSONUtil.parseObject(msg, MachMsg0x05.class);
            //转换数据
            AppDeviceObdLog log = this.translate(reqMsg);
            //处理数据
            obdDataMgr.addObdData(log);
        } catch (Exception ex) {
            logger.error("obd_data,消息处理失败", ex);
        }
    }


    /**
     * 转换数据
     *
     * @param reqMsg
     * @return
     */
    private AppDeviceObdLog translate(MachMsg0x05 reqMsg) {
        Gps gcj02Gps = mapApi.translateToGcj02(reqMsg.getLngWgs84(), reqMsg.getLatWgs84());
        MapLoc location = mapApi.geocode(gcj02Gps.getLng(), gcj02Gps.getLat());
        List<ObdFrameItem> obdFrameItemList = ObdDataUtil.parseObdData(reqMsg.getFrameId(), reqMsg.getFrameDataBytes());
        String frameDataDetail = JSONUtil.toString(obdFrameItemList);

        AppDeviceObdLog log = new AppDeviceObdLog();
        BeanUtils.copyProperties(reqMsg, log);
        log.setFrameIdHex(Long.toHexString(reqMsg.getFrameId()));
        log.setFrameDataDetail(frameDataDetail);
        log.setLng(gcj02Gps.getLng());
        log.setLat(gcj02Gps.getLat());
        if (location != null) {
            log.setLocation(location.getAddress());
            log.setProvince(location.getProvince());
            log.setCity(location.getCity());
        }
        return log;
    }
}
